﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Kooboo.IoC;
using Kooboo.Commerce;

namespace Kooboo.Web.Areas.Commerce.Binders
{
    public class ShippingBinder : EntityBinder
    {

        protected override string[] SkipProperties
        {
            get
            {
                return new string[]{"ShippingCostRules"};
            }
        }


        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var model = ObjectContainer.CreateInstance<IShipping>();

            var form = controllerContext.HttpContext.Request.Form;
            var indexes = form["ShippingCostRules.index"];


            model.ShippingCostRules = new List<IShippingCostRule>();

            if (string.IsNullOrWhiteSpace(indexes) == false)
            {
                foreach (var i in indexes.Split(','))
                {
                    var prefix = "ShippingCostRules[" + i + "]";

                    var rule = ObjectContainer.CreateInstance<IShippingCostRule>();

                    int id;
                    if(int.TryParse(form[prefix+".Id"],out id))
                    {
                        rule.Id = id;
                    }
                    else
                    {
                        rule.Id  =-1;
                    }

                    decimal from;
                    if (decimal.TryParse(form[prefix + ".From"], out from))
                    {
                        rule.From = from;
                    }
                    else
                    {
                        rule.From = decimal.Zero;
                    }

                    decimal to;
                    if (decimal.TryParse(form[prefix + ".To"], out to))
                    {
                        rule.To = to;
                    }
                    else
                    {
                        rule.To = decimal.Zero;
                    }

                    decimal cost;
                    if (decimal.TryParse(form[prefix + ".Cost"], out cost))
                    {
                        rule.Cost = cost;
                    }
                    else
                    {
                        rule.Cost = decimal.Zero;
                    }

                    model.ShippingCostRules.Add(rule);
                }
            }


            return model;

        }
    }
}
